#include "networkpropertydialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QIcon>
#include <QMessageBox>
#include <QGroupBox>
#include <QTabWidget>
#include <QFrame>
#include <QSpacerItem>
#include <QFont>
#include <QFontMetrics>
#include <QStackedLayout>
#include <QProcess>
#include <QApplication>
#include <QMainWindow>
#include "ipv4propertydialog.h"
#include <QSizePolicy>
#include <QThread> // Added for QThread::msleep
#include <QFile>
#include <QTextStream>

NetworkPropertyDialog::NetworkPropertyDialog(const ConnectionInfo &connInfo, const DeviceInfo &devInfo, QWidget *parent)
    : QDialog(parent), m_connInfo(connInfo), m_devInfo(devInfo)
{
    setWindowFlags((windowFlags() & ~Qt::WindowMaximizeButtonHint & ~Qt::WindowMinimizeButtonHint) | Qt::Dialog | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
      // 统一全局字体
    QFont globalFont("Microsoft YaHei UI", 10);
    this->setFont(globalFont);
    setWindowTitle(QString("%1 属性").arg(!connInfo.name.isEmpty() ? connInfo.name : devInfo.name));
    setFixedSize(435, 582); // Windows属性窗口标准尺寸
    setFixedSize(this->size());
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(12, 12, 12, 12);
    mainLayout->setSpacing(10);

    // 设置窗体背景色
    this->setStyleSheet("background:#F9F9F9;");

    // Windows风格按钮样式（更强优先级，边框加粗，全部!important，背景色#F3F3F3）
    QString btnStyle = R"(
QPushButton {
    border: 1.5px solid #A0A0A0 !important;
    background: #F3F3F3 !important;
    border-radius: 3px;
    padding: 2px 12px 2px 12px;
    min-width: 68px;
    min-height: 23px;
}
QPushButton:disabled {
    color: #A0A0A0 !important;
    background: #F5F5F5 !important;
    border: 1.5px solid #E0E0E0 !important;
}
QPushButton:hover, QPushButton:focus {
    border: 1.5px solid #3399FF !important;
    background: #E6F0FA !important;
}
)";
    this->setStyleSheet(this->styleSheet() + btnStyle);

    // 1. Tab栏
    QTabWidget *tabWidget = new QTabWidget(this);
    tabWidget->setFont(globalFont);
    tabWidget->setStyleSheet("QTabWidget::pane { background: #F0F0F0; border: none; }");
    QWidget *tabNetwork = new QWidget(this);
    QVBoxLayout *tabLayout = new QVBoxLayout(tabNetwork);
    tabLayout->setContentsMargins(0, 0, 0, 0);
    tabLayout->setSpacing(12);
    tabWidget->addTab(tabNetwork, "网络");
    mainLayout->addWidget(tabWidget);

    // 2. 顶部"连接时使用"标题和分组（严格贴合Windows）
    QLabel *connTitle = new QLabel("连接时使用:", tabNetwork);
    connTitle->setFont(QFont("Microsoft YaHei", 10, QFont::Bold));
    connTitle->setStyleSheet("color: #222; margin-bottom: 2px;");
    connTitle->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    tabLayout->addWidget(connTitle);
    QFrame *deviceFrame = new QFrame(tabNetwork);
    deviceFrame->setStyleSheet("QFrame { border: 1px solid #C0C0C0; border-radius: 6px; background: #fff; }");
    QHBoxLayout *deviceRow = new QHBoxLayout(deviceFrame);
    deviceRow->setContentsMargins(8, 6, 8, 6);
    deviceRow->setSpacing(8);
    QLabel *iconLabel = new QLabel(deviceFrame);
    iconLabel->setPixmap(QIcon(":/icons/resources/net_connected.png").pixmap(24, 24));
    iconLabel->setFixedSize(28, 28);
    iconLabel->setFrameStyle(QFrame::NoFrame);
    iconLabel->setStyleSheet("border:none;background:transparent;");
    deviceRow->addWidget(iconLabel, 0, Qt::AlignVCenter);
    // 名称和描述同一行，内容区分
    QString nameText = !devInfo.name.isEmpty() ? devInfo.name : (!connInfo.device.isEmpty() ? connInfo.device : connInfo.name);
    QString descText = !devInfo.model.isEmpty() ? devInfo.model : (!devInfo.driver.isEmpty() ? devInfo.driver : QString());
    QLabel *labelName = new QLabel(nameText, deviceFrame);
    labelName->setFont(QFont("Microsoft YaHei", 10, QFont::Bold));
    labelName->setFrameStyle(QFrame::NoFrame);
    labelName->setStyleSheet("color: #000000; background: transparent; border:none;");
    labelName->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    labelName->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
    deviceRow->addWidget(labelName, 0, Qt::AlignVCenter);
    QLabel *labelDesc = new QLabel(deviceFrame);
    labelDesc->setFont(globalFont);
    labelDesc->setFrameStyle(QFrame::NoFrame);
    labelDesc->setStyleSheet("color: #666666; background: transparent; margin-left:8px; border:none;");
    labelDesc->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    labelDesc->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
    if (descText.isEmpty()) {
        labelDesc->setVisible(false);
    } else {
        labelDesc->setVisible(true);
        labelDesc->setText(descText);
    }
    deviceRow->addWidget(labelDesc, 0, Qt::AlignVCenter);
    deviceRow->addStretch();
    tabLayout->addWidget(deviceFrame);
    // 配置按钮单独一行，右下角
    QHBoxLayout *configBtnLayout = new QHBoxLayout;
    configBtnLayout->addStretch();
    QPushButton *btnConfig = new QPushButton("配置(C)...", tabNetwork);
    btnConfig->setEnabled(true);
    btnConfig->setFont(globalFont);
    btnConfig->setFixedSize(100, 23);
    configBtnLayout->addWidget(btnConfig);
    tabLayout->addLayout(configBtnLayout);

    // 3. "此连接使用下列项目"分组
    QGroupBox *groupProto = new QGroupBox("此连接使用下列项目(O):", tabNetwork);
    groupProto->setFont(globalFont);
    QVBoxLayout *protoLayout = new QVBoxLayout(groupProto);
    protoLayout->setContentsMargins(12, 10, 12, 10);
    protoLayout->setSpacing(4);
    protocolList = new QListWidget(groupProto);
    protocolList->setFont(globalFont);
    protocolList->setSelectionMode(QAbstractItemView::SingleSelection);
    protocolList->setIconSize(QSize(16, 16));
    protocolList->setSpacing(2);
    protocolList->setFixedHeight(140);
    // IPv4 - 始终启用，不可修改
    QListWidgetItem *item4 = new QListWidgetItem(QIcon(":/icons/resources/net_connected.png"), "Internet 协议版本 4 (TCP/IPv4)");
    item4->setFlags(Qt::ItemIsEnabled); // 移除Qt::ItemIsUserCheckable，使其不可勾选
    item4->setCheckState(Qt::Checked);
    protocolList->addItem(item4);
    protocolItems["ipv4"] = item4;
    // IPv6
    QListWidgetItem *item6 = new QListWidgetItem(QIcon(":/icons/resources/wifi_connected.png"), "Internet 协议版本 6 (TCP/IPv6)");
    item6->setFlags(item6->flags() | Qt::ItemIsUserCheckable);
    item6->setCheckState(Qt::Checked);
    protocolList->addItem(item6);
    protocolItems["ipv6"] = item6;
    // 其它协议项（灰显，仅UI还原）
    QListWidgetItem *itemQoS = new QListWidgetItem(QIcon(":/icons/resources/dp.png"), "QoS 数据包计划程序");
    itemQoS->setFlags(Qt::NoItemFlags);
    itemQoS->setForeground(QColor(128, 128, 128));
    protocolList->addItem(itemQoS);
    QListWidgetItem *itemShare = new QListWidgetItem(QIcon(":/icons/resources/dp.png"), "Microsoft 网络的文件和打印机共享");
    itemShare->setFlags(Qt::NoItemFlags);
    itemShare->setForeground(QColor(128, 128, 128));
    protocolList->addItem(itemShare);
    protoLayout->addWidget(protocolList);
    // 协议按钮区（右对齐，宽度90）
    QHBoxLayout *protoBtnLayout = new QHBoxLayout;
    protoBtnLayout->addStretch();
    btnInstall = new QPushButton("安装(N)...", groupProto);
    btnInstall->setEnabled(true);
    btnInstall->setFont(globalFont);
    btnInstall->setFixedSize(100, 23);
    protoBtnLayout->addWidget(btnInstall);
    btnUninstall = new QPushButton("卸载(U)...", groupProto);
    btnUninstall->setEnabled(true);
    btnUninstall->setFont(globalFont);
    btnUninstall->setFixedSize(100, 23);
    protoBtnLayout->addWidget(btnUninstall);
    btnProperty = new QPushButton("属性(R)...", groupProto);
    btnProperty->setEnabled(true);
    btnProperty->setFont(globalFont);
    btnProperty->setFixedSize(100, 23);
    protoBtnLayout->addWidget(btnProperty);
    protoLayout->addLayout(protoBtnLayout);
    tabLayout->addWidget(groupProto);

    // 4. 描述区（极致还原Windows，label略压边框，边框更浅无圆角）
    QVBoxLayout *descBlockLayout = new QVBoxLayout;
    descBlockLayout->setContentsMargins(0, 0, 0, 0);
    descBlockLayout->setSpacing(0);

    QLabel *descTitle = new QLabel("描述", tabNetwork);
    descTitle->setFont(globalFont);
    descTitle->setStyleSheet("color: #666666; background: transparent; padding-left:2px; margin-bottom:-7px;");
    descTitle->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);

    QFrame *descFrame = new QFrame(tabNetwork);
    descFrame->setFrameShape(QFrame::Panel);
    descFrame->setFrameShadow(QFrame::Plain);
    descFrame->setLineWidth(1);
    descFrame->setStyleSheet("QFrame { background: transparent; border: 1px solid #cccccc; }");
    QVBoxLayout *descLayout = new QVBoxLayout(descFrame);
    descLayout->setContentsMargins(10, 8, 10, 8);
    descLayout->setSpacing(0);

    descLabel = new QLabel("选中协议后可点击属性进行详细配置。", descFrame);
    descLabel->setFont(globalFont);
    descLabel->setWordWrap(true);
    descLabel->setStyleSheet("color: #444444; background: transparent;");
    descLayout->addWidget(descLabel);

    descBlockLayout->addWidget(descTitle);
    descBlockLayout->addWidget(descFrame);
    tabLayout->addLayout(descBlockLayout);
    tabLayout->addStretch();

    // 5. 底部按钮区（右对齐）
    QHBoxLayout *bottomLayout = new QHBoxLayout;
    bottomLayout->addStretch();
    btnOk = new QPushButton("确定", this);
    btnOk->setFont(globalFont);
    btnOk->setFixedSize(75, 23);
    btnOk->setDefault(true);
    btnCancel = new QPushButton("取消", this);
    btnCancel->setFont(globalFont);
    btnCancel->setFixedSize(75, 23);
    bottomLayout->addWidget(btnOk);
    bottomLayout->addWidget(btnCancel);
    mainLayout->addLayout(bottomLayout);

    // 信号槽
    connect(protocolList, &QListWidget::currentItemChanged, this, [this](QListWidgetItem*, QListWidgetItem*){ updateDescription(); });
    connect(btnProperty, &QPushButton::clicked, this, &NetworkPropertyDialog::onPropertyClicked);
    connect(btnOk, &QPushButton::clicked, this, &NetworkPropertyDialog::onOkClicked);
    connect(btnCancel, &QPushButton::clicked, this, &NetworkPropertyDialog::onCancelClicked);
    connect(protocolList, &QListWidget::itemDoubleClicked, this, [this](QListWidgetItem*){ onPropertyClicked(); });
    // 加载协议状态
    loadProtocolStates();
    updateDescription();
    
    // 初始化IPv4设置
    m_ipv4Settings.hasChanges = false;
}

NetworkPropertyDialog::~NetworkPropertyDialog() {}

void NetworkPropertyDialog::loadProtocolStates() {
    // 读取当前连接协议状态，设置复选框
    QString dev = m_connInfo.device;
    QString conn = m_connInfo.name;
    if ((conn.isEmpty() || conn == dev) && !dev.isEmpty()) {
        QProcess proc;
        proc.start("nmcli", QStringList() << "-t" << "-f" << "NAME,DEVICE" << "connection" << "show");
        proc.waitForFinished();
        QString output = proc.readAllStandardOutput();
        for (const QString &line : output.split('\n')) {
            QStringList parts = line.split(':');
            if (parts.size() == 2 && parts[1] == dev) {
                conn = parts[0];
                break;
            }
        }
    }
    if (conn.isEmpty()) return;
    // 查询协议状态
    QProcess proc;
    proc.start("nmcli", QStringList() << "connection" << "show" << conn);
    proc.waitForFinished();
    QString output = proc.readAllStandardOutput();
    QString ipv4Method, ipv6Method;
    for (const QString &line : output.split('\n')) {
        if (line.trimmed().startsWith("ipv4.method"))
            ipv4Method = line.section(':', 1).trimmed();
        if (line.trimmed().startsWith("ipv6.method"))
            ipv6Method = line.section(':', 1).trimmed();
    }
    // IPv4始终勾选，IPv6根据实际状态设置
    protocolItems["ipv4"]->setCheckState(Qt::Checked); // IPv4始终启用
    protocolItems["ipv6"]->setCheckState((ipv6Method == "auto" || ipv6Method == "manual") ? Qt::Checked : Qt::Unchecked);
}

void NetworkPropertyDialog::saveProtocolStates() {
    QString dev = m_connInfo.device;
    QString conn = m_connInfo.name;
    if ((conn.isEmpty() || conn == dev) && !dev.isEmpty()) {
        QProcess proc;
        proc.start("nmcli", QStringList() << "-t" << "-f" << "NAME,DEVICE" << "connection" << "show");
        proc.waitForFinished();
        QString output = proc.readAllStandardOutput();
        for (const QString &line : output.split('\n')) {
            QStringList parts = line.split(':');
            if (parts.size() == 2 && parts[1] == dev) {
                conn = parts[0];
                break;
            }
        }
    }
    if (conn.isEmpty()) return;
    // 查询当前协议状态
    QProcess proc;
    proc.start("nmcli", QStringList() << "connection" << "show" << conn);
    proc.waitForFinished();
    QString output = proc.readAllStandardOutput();
    QString ipv4Method, ipv6Method;
    for (const QString &line : output.split('\n')) {
        if (line.trimmed().startsWith("ipv4.method"))
            ipv4Method = line.section(':', 1).trimmed();
        if (line.trimmed().startsWith("ipv6.method"))
            ipv6Method = line.section(':', 1).trimmed();
    }
    // IPv4始终启用，但不修改其方法（让applyIPv4Settings来处理）
    // 只有在没有IPv4设置更改时才确保为auto模式
    if (!m_ipv4Settings.hasChanges) {
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.method" << "auto");
    }
    // IPv6
    bool ipv6Checked = protocolItems["ipv6"]->checkState() == Qt::Checked;
    if (!ipv6Checked) {
        if (ipv6Method == "manual") {
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv6.method" << "auto");
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv6.addresses" << "");
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv6.gateway" << "");
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv6.dns" << "");
        }
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv6.method" << "ignore");
    } else {
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv6.method" << "auto");
    }
    // 不再在这里down/up连接
    // 立即刷新主界面网络信息
    QWidget *p = this->parentWidget();
    while (p && !qobject_cast<QMainWindow*>(p)) p = p->parentWidget();
    if (auto mainWin = qobject_cast<QMainWindow*>(p)) {
        QMetaObject::invokeMethod(mainWin, "onNetworkInfoUpdated");
    }
}

void NetworkPropertyDialog::updateDescription() {
    QListWidgetItem *cur = protocolList->currentItem();
    if (!cur) {
        descLabel->setText("选中协议后可点击属性进行详细配置。");
        btnProperty->setEnabled(false);
        return;
    }
    if (cur == protocolItems["ipv4"]) {
        descLabel->setText("Internet 协议版本 4 (TCP/IPv4)：用于大多数网络通信，可配置IP、网关、DNS等。");
        btnProperty->setEnabled(true);
    } else if (cur == protocolItems["ipv6"]) {
        descLabel->setText("Internet 协议版本 6 (TCP/IPv6)：支持下一代互联网地址，可配置IPv6地址、网关、DNS等。");
        btnProperty->setEnabled(true);
    } else {
        descLabel->setText("仅支持IPv4/IPv6协议的启用、禁用和配置。");
        btnProperty->setEnabled(false);
    }
}

void NetworkPropertyDialog::onPropertyClicked() {
    QListWidgetItem *cur = protocolList->currentItem();
    if (cur == protocolItems["ipv4"]) {
        IPv4PropertyDialog dlg(m_connInfo, m_devInfo, this);
        if (dlg.exec() == QDialog::Accepted) {
            // 保存IPv4设置
            QString ip, mask, gw, dns1, dns2;
            bool validate, autoConnect;
            int dnsPriorityLevel = 0;
            dlg.getValues(ip, mask, gw, dns1, dns2, validate, autoConnect, dnsPriorityLevel);
            int dnsPriority = 100;
            if (dnsPriorityLevel == 0) dnsPriority = 200;
            else if (dnsPriorityLevel == 1) dnsPriority = 100;
            else dnsPriority = 0;
            m_ipv4Settings.autoIP = dlg.isAutoIP();
            m_ipv4Settings.ip = ip;
            m_ipv4Settings.mask = mask;
            m_ipv4Settings.gateway = gw;
            m_ipv4Settings.autoDNS = dlg.isAutoDNS();
            m_ipv4Settings.dns1 = dns1;
            m_ipv4Settings.dns2 = dns2;
            m_ipv4Settings.autoConnect = autoConnect;
            m_ipv4Settings.dnsPriority = dnsPriority;
            m_ipv4Settings.hasChanges = true;
            // 多IP
            m_ipv4Settings.ipList = dlg.getIpList();
            // 多网关
            m_ipv4Settings.gatewayList = dlg.getGatewayList();
        }
    } else if (cur == protocolItems["ipv6"]) {
        QMessageBox::information(this, "IPv6属性", "这里弹出IPv6详细配置窗口（待实现）");
    }
}

void NetworkPropertyDialog::onOkClicked() {
    
    // 先应用IPv4设置（包括清空字段、设置method等）
    if (m_ipv4Settings.hasChanges) {
        applyIPv4Settings();
    }
    // 再保存协议状态（不再在saveProtocolStates里down/up连接）
    saveProtocolStates();
    
    accept();
}

void NetworkPropertyDialog::onCancelClicked() {
    reject();
}

void NetworkPropertyDialog::applyIPv4Settings() {
    
    // 获取连接名称
    QString dev = !m_connInfo.device.isEmpty() ? m_connInfo.device : m_devInfo.name;
    QString conn = m_connInfo.name;
    
    if ((conn.isEmpty() || conn == dev) && !dev.isEmpty()) {
        
        QProcess proc;
        proc.start("nmcli", QStringList() << "-t" << "-f" << "NAME,DEVICE" << "connection" << "show");
        proc.waitForFinished();
        QString output = proc.readAllStandardOutput();
        
        for (const QString &line : output.split('\n')) {
            QStringList parts = line.split(':');
            if (parts.size() == 2 && parts[1] == dev) {
                conn = parts[0];
                break;
            }
        }
    }
    // 新增：如果conn仍为空，尝试通过interface-name查找profile
    if (conn.isEmpty() && !dev.isEmpty()) {
        conn = IPv4PropertyDialog::findProfileNameByDevice(dev);
    }
    
    if (conn.isEmpty()) {
        return;
    }
    
    // 检测当前连接状态
    bool wasConnected = false;
    QProcess statusProc;
    statusProc.start("nmcli", QStringList() << "-t" << "-f" << "NAME,STATE" << "connection" << "show" << "--active");
    statusProc.waitForFinished();
    QString statusOutput = statusProc.readAllStandardOutput();
    QStringList activeConnections = statusOutput.split('\n', Qt::SkipEmptyParts);
    
    for (const QString &line : activeConnections) {
        QStringList parts = line.split(':');
        if (parts.size() == 2 && parts[0] == conn) {
            wasConnected = true;
            break;
        }
    }
    
    // 如果连接是活跃状态，先断开连接以避免配置冲突
    if (wasConnected) {
        QProcess::execute("nmcli", QStringList() << "connection" << "down" << conn);
        // 等待200ms，确保NetworkManager释放配置文件锁
        QThread::msleep(200);
    }
    
    // 根据IP设置模式应用配置
    if (m_ipv4Settings.autoIP) {
        // 完全自动获取模式
        // 先切method=auto，再清空其它字段
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.method" << "auto");
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.addresses" << "");
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.gateway" << "");
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.dns" << "");
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.routes" << "");
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.ignore-auto-dns" << "no");
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.ignore-auto-routes" << "no");
        // 检查ifcfg配置文件是否还存在IPADDR字段
        QString ifcfgPath = QString("/etc/sysconfig/network-scripts/ifcfg-%1").arg(dev);
        QFile ifcfgFile(ifcfgPath);
        if (ifcfgFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&ifcfgFile);
            bool hasIPADDR = false;
            while (!in.atEnd()) {
                QString line = in.readLine();
                if (line.trimmed().startsWith("IPADDR")) {
                    hasIPADDR = true;
                    break;
                }
            }
            ifcfgFile.close();
            if (hasIPADDR) {
                QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.addresses" << "");
            }
        }
    } else {
        // 只要是手动IP模式
        if (!m_ipv4Settings.ipList.isEmpty()) {
            // 多IP写入
            QStringList addrList;
            for (const auto &pair : m_ipv4Settings.ipList) {
                QString ip = pair.first;
                QString mask = pair.second;
            // 计算CIDR
                QStringList maskParts = mask.split('.');
                int cidr = 0;
                if (maskParts.size() == 4) {
                    for (int i = 0; i < 4; i++) {
                        int octet = maskParts[i].toInt();
                        while (octet > 0) {
                            if (octet & 1) cidr++;
                            octet >>= 1;
                        }
                    }
                }
                addrList << QString("%1/%2").arg(ip).arg(cidr);
            }
            QString addresses = addrList.join(",");
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.addresses" << addresses);
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.method" << "manual");
            if (!m_ipv4Settings.gateway.isEmpty()) {
                QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.gateway" << m_ipv4Settings.gateway);
            }
        } else if (!m_ipv4Settings.ip.isEmpty() && !m_ipv4Settings.mask.isEmpty()) {
            // 兼容单IP逻辑
            QStringList maskParts = m_ipv4Settings.mask.split('.');
            int cidr = 0;
            if (maskParts.size() == 4) {
                for (int i = 0; i < 4; i++) {
                    int octet = maskParts[i].toInt();
                    while (octet > 0) {
                        if (octet & 1) cidr++;
                        octet >>= 1;
                    }
                }
            }
            QString address = QString("%1/%2").arg(m_ipv4Settings.ip).arg(cidr);
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.addresses" << address);
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.method" << "manual");
            if (!m_ipv4Settings.gateway.isEmpty()) {
                QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.gateway" << m_ipv4Settings.gateway);
            }
        } else {
            // 清空静态IP，保持manual
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.addresses" << "");
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.gateway" << "");
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.method" << "manual");
        }
    }
    
    // 多网关写入
    if (!m_ipv4Settings.gatewayList.isEmpty()) {
        // 主网关
        QString mainGw = m_ipv4Settings.gatewayList[0].first;
        int mainMetric = m_ipv4Settings.gatewayList[0].second;
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.gateway" << mainGw);
        // 其他网关写入routes
        QStringList routeList;
        for (int i = 1; i < m_ipv4Settings.gatewayList.size(); ++i) {
            QString gw = m_ipv4Settings.gatewayList[i].first;
            int metric = m_ipv4Settings.gatewayList[i].second;
            QString metricStr = (metric < 0) ? "" : QString::number(metric);
            // 0.0.0.0/0 网关 metric
            routeList << QString("0.0.0.0/0 %1 %2").arg(gw).arg(metricStr);
        }
        QString routes = routeList.join(",");
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.routes" << routes);
    }
    
    // 根据DNS设置模式应用配置
    if (m_ipv4Settings.autoDNS) {
        // 自动DNS模式
        
        if (m_ipv4Settings.autoIP) {
            // 完全自动模式：让DHCP提供DNS
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.ignore-auto-dns" << "no");
        } else {
            // 手动IP + 自动DNS：从DHCP获取DNS，但保持手动IP
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.ignore-auto-dns" << "no");
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.ignore-auto-routes" << "yes");
        }
    } else {
        // 手动DNS模式
        
        QStringList dnsList;
        if (!m_ipv4Settings.dns1.isEmpty()) {
            dnsList.append(m_ipv4Settings.dns1);
        }
        if (!m_ipv4Settings.dns2.isEmpty()) {
            dnsList.append(m_ipv4Settings.dns2);
        }
        
        if (!dnsList.isEmpty()) {
            QString dnsString = dnsList.join(',');
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.dns" << dnsString);
            QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.dns-priority" << QString::number(m_ipv4Settings.dnsPriority));
        }
        
        // 忽略自动DNS
        QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "ipv4.ignore-auto-dns" << "yes");
    }
    
    // 应用自动连接设置
    QString autoConnectValue = m_ipv4Settings.autoConnect ? "yes" : "no";
    QProcess::execute("nmcli", QStringList() << "connection" << "modify" << conn << "connection.autoconnect" << autoConnectValue);
    
    // 如果之前是连接状态，重新激活连接以应用设置
    if (wasConnected) {
        QProcess::execute("nmcli", QStringList() << "connection" << "up" << conn);
    }
    
    // 立即刷新主界面网络信息
    QWidget *p = this->parentWidget();
    while (p && !qobject_cast<QMainWindow*>(p)) p = p->parentWidget();
    if (auto mainWin = qobject_cast<QMainWindow*>(p)) {
        QMetaObject::invokeMethod(mainWin, "onNetworkInfoUpdated");
    }
}

void NetworkPropertyDialog::onProtocolSelectionChanged() {}
void NetworkPropertyDialog::onProtocolToggled(QListWidgetItem*) {} 